﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using FanaticRock.AudioManage.Helpers;
using FanaticRock.Core.Extensions;
using FanaticRock.Core.Models;
using FanaticRock.DownloadManage.Helpers;
using FanaticRock.Extensions;
using FanaticRock.Helpers;
using FanaticRock.MediaSource.BilibiliAPI.API.Fav.Folder;
using FanaticRock.MediaSource.BilibiliAPI.Helpers;
using FanaticRock.Theme.Helpers;
using FanaticRock.ViewModels.Download;
using System.Collections.ObjectModel;
using System.IO;
using ThrottleDebounce;

namespace FanaticRock.ViewModels
{
    // DownloadListPart
    public partial class MainViewModel
    {
        #region fields

        // 下载的缓存列表，因为下载服务的通知返回的是uri，所以并不知道到底下载过来的是哪个任务，为此这里建立了一个字典来进行下载项的映射。
        // 以保证下载项能顺利通知到指定地方。
        private Dictionary<string, DownloadBvidSongViewModel> _downloadListCache = new();
        private RateLimitedAction _delaySaveListAction;

        #endregion

        #region props

        ///<summary>已下载项的列表。</summary>
        [ObservableProperty]
        private ObservableCollection<DownloadBvidSongViewModel> _downloadList = new();

        #endregion

        #region ctors

        private void InitDownloadListPart()
        {
            _delaySaveListAction = Debouncer.Debounce(() =>
           {
               _playListService.SaveList(true);
               this.Info("MainViewModel._downloadManageService_DownloadCompleted: 信息已保存");

           }, TimeSpan.FromSeconds(5));
        }

        #endregion

        #region event impls

        // 当下载完成时执行该内容，主要会进行封面的追加，并最后标识任务完成。
        private async void _downloadManageService_DownloadCompleted(object? sender, Core.Download.FileDownloadCompletedEventArgs e)
        {
            try
            {
                var uri = e.Uri;
                if (_downloadListCache.TryGetValue(uri, out var item))
                {
                    var imgPng = ResourceSourceHelper.GetUri(item.CoverSource);

                    var bytes = await DownloadBytesHelper.GetBytes(WebPUriHelper.GetJpg(imgPng, 400, 400));
                    //bytes = PngHelper.GetBytesFromWebP(bytes);

                    //File.WriteAllBytes(filePath, bytes);
                    //var bytes = ms.ToArray();

                    //var filePath = Path.Combine(Path.GetDirectoryName(item.LocalPath), "cover.png");

                    //File.WriteAllBytes(filePath, bytes);

                    var originSource = ImageHelper.CreateImageSource(bytes);

                    AudioFormatHelper.SetCover(item.LocalPath, bytes);

                    var coverPath = Path.Combine(Path.GetDirectoryName(item.LocalPath), "cover.jpg");
                    await File.WriteAllBytesAsync(coverPath, bytes);

                    item.CoverSource = new UriResourceSource(coverPath);

                    await Task.Delay(100);
                    item.IsCompleted = true;

                    _downloadList.UpdateIndex();

                    await _playListService.AddSong(item.Export());

                    NoticeHelper.Notice("信息准备完成", $"{item.Title} 已下载完成并加入到播放列表");

                    _delaySaveListAction?.Invoke();

                }
            }
            catch (Exception ex)
            {
                this.Info($"MainViewModel._downloadManageService_DownloadCompleted: {ex}");
            }
            finally
            {
                e.IsHandled = true;
            }

        }

        // 更新下载进度。
        private void _downloadManageService_DownloadProgress(object? sender, Core.Download.FileDownloadProgressEventArgs e)
        {
            var uri = e.Uri;
            if (_downloadListCache.TryGetValue(uri, out var item))
            {
                item.Progress = e.Progress;
            }
        }

        #endregion

        #region methods

        ///<summary>初始化列表。</summary>
        private async void InitDownloadList()
        {
            var storage = await _downloadManageService.GetStorage();
            var viewModels = storage.Select(i => new DownloadBvidSongViewModel(i));
            _downloadList = new ObservableCollection<DownloadBvidSongViewModel>(viewModels);
            _downloadList.UpdateIndex();
        }

        public void AddDownloadItem(DownloadBvidSongViewModel downloadItem)
        {
            if (downloadItem == null) return;
            if (string.IsNullOrWhiteSpace(downloadItem.BaseUri)) return;
            DownloadList.Add(downloadItem);
            _downloadListCache.Add(downloadItem.BaseUri, downloadItem);
            _downloadList.UpdateIndex();
        }

        public void RemoveDownloadItem(DownloadBvidSongViewModel downloadItem)
        {
            DownloadList.Remove(downloadItem);
            _downloadListCache.Remove(downloadItem.BaseUri);
            _downloadList.UpdateIndex();
        }


        [RelayCommand]
        public void ClearDownloadList()
        {
            ClearAllDownloadItem();
        }

        private void ClearAllDownloadItem()
        {
            _downloadListCache.Clear();
            DownloadList.Clear();
            _downloadManageService.Clear();

            NoticeHelper.Notice($"下载列表清理完成");

        }

        #endregion
    }
}
